<?php

namespace app\admin\model;

use app\common\enums\StatusEnum;

class LangClassReciteAnswer extends \app\common\model\LangClassReciteAnswer
{
    /**
     * 添加语种显示的班级
     * @param $reciteId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getListByRecite($reciteId)
    {
        $resultCount = 0;
        if ($reciteId > 0) {
            $result = static::field('id, answer, image, is_right')
                ->where(['recite_id' => $reciteId, 'status' => StatusEnum::ENABLED])
                ->select()
                ->toArray();
            $resultCount = count($result);
        }
        if($resultCount == 0 || $reciteId <= 0){
            $result = [
                0 => [
                    'id' => 0,
                    'answer' => '',
                    'image' => '',
                    'is_right' => 0,
                ],
            ];
            array_push($result, $result[0], $result[0], $result[0]);
        }
        
        $label = ['答案A', '答案B', '答案C', '答案D'];
        foreach ($result as $key => $value) {
            $result[$key]['label'] = isset($label[$key]) ? $label[$key] : '未知';
        }
        //print_r($result);
        return $result;
    }

    /**
     * 添加背单词、背句子
     * @param $reciteId
     * @param $rightKey
     * @param $data
     * @throws \Exception
     */
    public static function saveData($reciteId, $rightKey, $data)
    {
        $model = new LangClassReciteAnswer();
        $answer = [];
        
        foreach ($data as $key => $value) {
            $images = explode(",",$value['image']);

            $answer[$key] = [
                'recite_id' => $reciteId,
                'answer' => $value['answer'],
                'image' => $images[count($images) - 1],
                'is_right' => ($key == $rightKey) ? self::RIGHT : self::RIGHT_NO,
                'status' => StatusEnum::ENABLED,
            ];
            // 包含主键更新数据
            if (isset($value['id']) && $value['id'] > 0) {
                $answer[$key]['id'] = $value['id'];
            }
        }
        if ($answer) {
            // 添加新的数据
            $model->saveAll($answer);
        }
    }

    /**
     * 删除记录
     * @param $reciteId
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function deleteData($reciteId)
    {
        static::where(['recite_id' => $reciteId])->delete();
    }
}